package rtool

import (
	"bytes"
	"errors"
	"fmt"
	"golang.org/x/image/bmp"
	"golang.org/x/image/tiff"
	"golang.org/x/image/webp"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"strings"
)

func ToPNG(imgContent []byte, imgType string) ([]byte, error) {
	return imgToImg(imgContent, imgType, "png")
}

func ToJPEG(imgContent []byte, imgType string) ([]byte, error) {
	return imgToImg(imgContent, imgType, "jpeg")
}

func imgToImg(imgContent []byte, imgType string, toType string) ([]byte, error) {
	reader := bytes.NewReader(imgContent)
	var img image.Image
	var err error
	switch imgType {
	case "jpg":
		img, err = jpeg.Decode(reader)
	case "jpeg":
		img, err = jpeg.Decode(reader)
	case "png":
		img, err = png.Decode(reader)
	case "gif":
		img, err = gif.Decode(reader)
	case "webp":
		img, err = webp.Decode(reader)
	case "bmp":
		img, err = bmp.Decode(reader)
	case "tiff":
		img, err = tiff.Decode(reader)
	default:
		return nil, errors.New("不支持的来源格式")
	}
	if err != nil {
		return nil, fmt.Errorf("解码图像失败: %w", err)
	}
	buffer := bytes.NewBuffer(nil)
	switch toType {
	case "jpg", "jpeg":
		err = jpeg.Encode(buffer, img, nil)
	case "png":
		err = png.Encode(buffer, img)
	case "gif":
		err = gif.Encode(buffer, img, nil)
	//case "webp":
	//	err = webp.Encode(buffer, img)
	case "bmp":
		err = bmp.Encode(buffer, img)
	case "tiff":
		err = tiff.Encode(buffer, img, nil)
	default:
		return nil, errors.New("不支持的转换格式")
	}
	if err != nil {
		return nil, fmt.Errorf("编码为 %v 失败: %w", strings.ToUpper(toType), err)
	}
	return buffer.Bytes(), nil
}
